package com.hanson.controller;

import com.alibaba.fastjson.JSONObject;
import com.hanson.common.bean.ResultMessage;
import com.hanson.common.bean.SearchBean;
import com.hanson.common.bean.ShareConfigBean;
import com.hanson.common.bean.WeiXinConfig;
import com.hanson.common.service.RedisService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.common.util.FileUploadUtil;
import com.hanson.common.util.WeiXinShareUtil;
import com.hanson.entity.*;
import com.hanson.service.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.enums.TicketType;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/web")
public class WebIndexController {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private GoodsTypeService goodsTypeService;
    @Autowired
    private GoodsRuleService goodsRuleService;
    @Autowired
    private WeiXinConfig weiXinConfig;
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserAddressService userAddressService;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ApplyInfoService applyInfoService;
    @Autowired
    private SpreadInfoService spreadInfoService;
    @Autowired
    private SearchSortService searchSortService;
    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private GroupGoodsService groupGoodsService;
    @Autowired
    private GoodsCommentService goodsCommentService;
    @Autowired
    private IndexSlideService indexSlideService;
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private AcctbkService acctbkService;
    @Autowired
    private GoodsCollectService goodsCollectService;
    @Autowired
    private RedisService redisService;
    @Value("${oss.local}")
    private String isLocal;


    /**
     * 首页
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap) throws Exception {
        long time1 = System.currentTimeMillis();
        SearchBean hotBean = new SearchBean();
        hotBean.setIsHot(1);
        modelMap.put("hotData", goodsService.getSimpleGoodsList(1, 3, hotBean, modelMap));

        SearchBean benefitBean = new SearchBean();
        benefitBean.setIsBenefit(1);
        modelMap.put("benefitData", goodsService.getSimpleGoodsList(1, 4, benefitBean, modelMap));

        SearchBean bestBean = new SearchBean();
        hotBean.setIsBest(1);
        modelMap.put("bestData", goodsService.getSimpleGoodsList(1, 4, bestBean, modelMap));
        modelMap.put("seconds", String.valueOf(seckillGoodsService.getSurplusSecond()));
        modelMap.put("slide", indexSlideService.selectAll());
        modelMap.put("index", 1);
        long time2 = System.currentTimeMillis();
        log.error("【查询首页数据 花费时间：{}】", time2 - time1);
        BusinessUtil.getIpAddr();
        return "web/index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap modelMap) throws Exception {
        return "web/login";
    }

    /**
     * 搜索页面
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(ModelMap modelMap) {
        modelMap.put("data", searchSortService.findZset(0, 5));
        modelMap.put("recommend", goodsService.getRecommendGoods());
        BusinessUtil.getIpAddr();
        return "web/search";
    }

    /**
     * 搜索结果页面
     *
     * @param modelMap
     * @param searchBean
     * @return
     */
    @RequestMapping(value = "/searchResult", method = RequestMethod.GET)
    public String searchResult(ModelMap modelMap, SearchBean searchBean) {
        if (StringUtils.isNotEmpty(searchBean.getKeyWords())) {
            searchSortService.sort(searchBean.getKeyWords());
        }
        modelMap.put("data", goodsService.getSimpleGoodsList(0, 20, searchBean, modelMap));
        modelMap.put("isBest", searchBean.getIsBest());
        modelMap.put("sortPrice", searchBean.getSortPrice());
        modelMap.put("sortSales", searchBean.getSortSales());
        modelMap.put("keyWords", searchBean.getKeyWords());
        BusinessUtil.getIpAddr();
        return "web/searchResult";
    }

    @RequestMapping(value = "/searchType", method = RequestMethod.GET)
    public String searchType(ModelMap modelMap, String typeId) {
        modelMap.put("data", goodsService.getSimpleGoodsByType(Integer.parseInt(typeId), modelMap));
        modelMap.put("isBest", 0);
        modelMap.put("sortPrice", 0);
        modelMap.put("sortSales", 0);
        BusinessUtil.getIpAddr();
        return "web/searchResult";
    }

    @RequestMapping(value = "/hotMore", method = RequestMethod.GET)
    public String hotMore(ModelMap modelMap, String keyWords) {
        SearchBean searchBean = new SearchBean();
        searchBean.setIsHot(1);
        modelMap.put("data", goodsService.getSimpleGoodsList(0, 20, searchBean, modelMap));
        BusinessUtil.getIpAddr();
        return "web/hotMore";
    }

    @RequestMapping(value = "/benefitMore", method = RequestMethod.GET)
    public String benefitMore(ModelMap modelMap, String keyWords) {
        SearchBean searchBean = new SearchBean();
        searchBean.setIsBenefit(1);
        modelMap.put("data", goodsService.getSimpleGoodsList(0, 20, searchBean, modelMap));
        BusinessUtil.getIpAddr();
        return "web/benefitMore";
    }

    @RequestMapping(value = "/bestMore", method = RequestMethod.GET)
    public String bestMore(ModelMap modelMap, String keyWords) {
        SearchBean searchBean = new SearchBean();
        searchBean.setIsBest(1);
        modelMap.put("data", goodsService.getSimpleGoodsList(0, 20, searchBean, modelMap));
        BusinessUtil.getIpAddr();
        return "web/bestMore";
    }

    /**
     * 分类搜索模板
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/category", method = RequestMethod.GET)
    public String category(ModelMap modelMap, @RequestParam(defaultValue = "1") String type) {
        List<GoodsTypeBean> typeList = goodsTypeService.selecPidAndType(0, Integer.parseInt(type));
        modelMap.put("types", typeList);
        modelMap.put("typesData", goodsTypeService.selectByPids(typeList));
        modelMap.put("category", 1);
        modelMap.put("type", Integer.parseInt(type));
        BusinessUtil.getIpAddr();
        return "web/category";
    }

    /**
     * 分享页面进入详情
     *
     * @param request
     * @param goodsId
     * @param parentId
     * @param type
     * @return
     */
    @RequestMapping(value = "/shareDetail/{goodsId}/{parentId}/{type}", method = RequestMethod.GET)
    public String shareDetail(HttpServletRequest request, @PathVariable("goodsId") String goodsId, @PathVariable("parentId") String parentId, @PathVariable("type") String type) {
//        String openId = BusinessUtil.getCookieToken(request, "openId");
//        if (StringUtils.isNotEmpty(parentId) && StringUtils.isNotEmpty(openId) && StringUtils.isNotEmpty(goodsId)) {
//            if(!parentId.equals(openId)){
//                String key = String.format(Const.SHARE_GOODS_KEY, goodsId);
//                if (redisService.hasKey(key)) {
//                    redisService.hset(key, openId, parentId, 60 * 60 * 24 * 7L);
//                } else {
//                    Map<String, Object> shareMap = Maps.newHashMap();
//                    shareMap.put(openId, parentId);
//                    redisService.hmset(key, shareMap, 60 * 60 * 24 * 7L);
//                }
//            }
//        }
        UserBean parentUserBean = userService.selectByOpenId(parentId);
        String webParentId = "0";
        if (null != parentUserBean && parentUserBean.getIsSpread() == 1) {
            //是经销商
            webParentId = parentId;
        }
        if (type.equals("1")) {
            return "redirect:/web/goodsDetail/" + goodsId + "?parentId=" + webParentId;
        } else if (type.equals("2")) {
            return "redirect:/web/groupDetail/" + goodsId + "?parentId=" + webParentId;
        } else if (type.equals("3")) {
            return "redirect:/web/skillDetail/" + goodsId + "?parentId=" + webParentId;
        }
        BusinessUtil.getIpAddr();
        return "web/error";
    }

    /**
     * 商品详情
     *
     * @param modelMap
     * @param id
     * @return
     */
    @RequestMapping(value = "/goodsDetail/{id}", method = RequestMethod.GET)
    public String goodsDetail(ModelMap modelMap, @PathVariable("id") String id, String parentId, HttpServletRequest request) throws WxErrorException {
        GoodsBean goodsBean = goodsService.detail(Integer.parseInt(id));
        if(null == goodsBean){
            modelMap.put("msg","商品已下架");
            return "web/error";
        }
        modelMap.put("data", goodsBean);
        String openId = BusinessUtil.getCookieToken(request, "openId");
        if (StringUtils.isNotEmpty(openId)) {
            modelMap.put("cartCount", cartService.countByOpenId(openId));
            int count = goodsCollectService.count(openId, Integer.parseInt(id));
            UserBean userBean = userService.selectByOpenId(openId);
            if (null == userBean) {
                modelMap.put("isVip", 0);
            } else {
                modelMap.put("isVip", userBean.getIsVip());
            }
            modelMap.put("isCollect", count);
        } else {
            modelMap.put("cartCount", 0);
            modelMap.put("isCollect", 0);
        }
        modelMap.put("comment", goodsCommentService.selectByGoodsId(Integer.parseInt(id), 0, modelMap));
        String url = String.format("%sweb/shareDetail/%s/%s/%s", weiXinConfig.getDomian(), goodsBean.getId(), openId, "1");
        ShareConfigBean shareConfigBean = WeiXinShareUtil.getWxConfig(request, weiXinConfig.getAppId(), wxMpService.getTicket(TicketType.JSAPI));
        shareConfigBean.setTitle("优质商品，为您推荐>>>");
        shareConfigBean.setDesc(goodsBean.getGoodsName());
        shareConfigBean.setImgUrl(goodsBean.getImage());
        shareConfigBean.setLink(url);
        modelMap.put("share", shareConfigBean);
        modelMap.put("parentId", StringUtils.isEmpty(parentId) ? "0" : parentId);
        BusinessUtil.getIpAddr();
        return "web/goodsDetail";
    }

    /**
     * 个人中心
     *
     * @param modelMap
     * @return
     */
    @RequestMapping(value = "/userCenter", method = RequestMethod.GET)
    public String userCenter(ModelMap modelMap, HttpServletRequest request, String parentId) throws Exception {
        String openId = BusinessUtil.getCookieToken(request, "openId");
        modelMap.put("userCenter", 1);
        modelMap.put("data", userService.selectByOpenId(openId));
        if (StringUtils.isNotEmpty(parentId)) {
            UserBean userBean = userService.selectByOpenId(parentId);
            if (null != userBean) {
                modelMap.put("parentId", parentId);
                modelMap.put("parentName", userBean.getNickName());
            } else {
                modelMap.put("parentId", 0);
            }
        } else {
            modelMap.put("parentId", 0);
        }
        List<Map<Integer, Integer>> staticMap = orderService.groupByStatus(openId);
        Map<String, Integer> dataMap = new HashMap<>();
        dataMap.put("status1", 0);
        dataMap.put("status2", 0);
        dataMap.put("status3", 0);
        dataMap.put("status4", 0);
        dataMap.put("status5", 0);
        dataMap.put("status6", 0);
        if (CollectionUtils.isNotEmpty(staticMap)) {
            staticMap.stream().forEach(c -> {
                dataMap.put("status" + c.get("STATUS"), c.get("num"));
            });
        }
        modelMap.put("groupOrder", dataMap);
        BusinessUtil.getIpAddr();
        return "web/userCenter";
    }

    /**
     * 地址列表
     *
     * @param modelMap
     * @param openId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addressList", method = RequestMethod.GET)
    public String addressList(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        modelMap.put("data", userAddressService.selectByOpenId(openId));
        BusinessUtil.getIpAddr();
        return "web/addressList";
    }

    /**
     * 新增地址
     *
     * @param modelMap
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addressAdd", method = RequestMethod.GET)
    public String addressAdd(ModelMap modelMap, String id, String type) throws Exception {
        if (StringUtils.isNotEmpty(id)) {
            modelMap.put("data", userAddressService.selectById(id));
        }
        if (StringUtils.isNotEmpty(type)) {
            modelMap.put("type", type);
        }
        BusinessUtil.getIpAddr();
        return "web/addressAdd";
    }

    /**
     * 购物车
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cartList", method = RequestMethod.GET)
    public String cartList(ModelMap modelMap, HttpServletRequest request) throws Exception {
        String openId = BusinessUtil.getCookieToken(request, "openId");
        List<CartBean> cartBeanList = cartService.selectByOpenId(openId, modelMap);
        modelMap.put("data", cartBeanList);
        modelMap.put("cart", 1);
        modelMap.put("recommend", goodsService.getRecommendGoods());
        BusinessUtil.getIpAddr();
        return "web/cartList";
    }

    /**
     * 新增评论
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addComment/{id}", method = RequestMethod.GET)
    public String addComment(ModelMap modelMap, @PathVariable String id) throws Exception {
        OrderBean orderBean = orderService.selectDetail(id);
        modelMap.put("data", orderBean);
        modelMap.put("orderId", id);
        BusinessUtil.getIpAddr();
        return "web/addComment";
    }

    /**
     * 评论列表
     *
     * @param modelMap
     * @param scoreType
     * @param goodsId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/commentList/{scoreType}/{goodsId}", method = RequestMethod.GET)
    public String commentList(ModelMap modelMap, @PathVariable String scoreType, @PathVariable String goodsId) throws Exception {
        modelMap.put("data", goodsCommentService.selectByGoodsId(Integer.parseInt(goodsId), Integer.parseInt(scoreType), modelMap));
        modelMap.put("scoreType", scoreType);
        modelMap.put("goodsId", goodsId);
        BusinessUtil.getIpAddr();
        return "web/commentList";
    }


    /**
     * 秒杀
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/skillGoods", method = RequestMethod.GET)
    public String skillGoods(ModelMap modelMap) throws Exception {
        modelMap.put("data", seckillGoodsService.getSkillTimeData(modelMap));
        modelMap.put("seconds", String.valueOf(seckillGoodsService.getSurplusSecond()));
        BusinessUtil.getIpAddr();
        return "web/skillGoods";
    }

    /**
     * 秒杀详情
     *
     * @param modelMap
     * @param id
     * @return
     */
    @RequestMapping(value = "/skillDetail/{id}", method = RequestMethod.GET)
    public String skillDetail(ModelMap modelMap, @PathVariable("id") String id, HttpServletRequest request, String parentId, @CookieValue("openId") String openId) throws WxErrorException {
        SeckillGoodsBean seckillGoodsBean = seckillGoodsService.selectById(Integer.parseInt(id));
        GoodsBean goodsBean = goodsService.detail(seckillGoodsBean.getGoodsId());
        modelMap.put("killData", seckillGoodsBean);
        modelMap.put("data", goodsBean);
        modelMap.put("comment", goodsCommentService.selectByGoodsId(goodsBean.getId(), 0, modelMap));
        String url = String.format("%sweb/shareDetail/%s/%s/%s", weiXinConfig.getDomian(), seckillGoodsBean.getId(), openId, "3");
        ShareConfigBean shareConfigBean = WeiXinShareUtil.getWxConfig(request, weiXinConfig.getAppId(), wxMpService.getTicket(TicketType.JSAPI));
        shareConfigBean.setTitle("秒杀商品，为您推荐>>>");
        shareConfigBean.setDesc(goodsBean.getGoodsName());
        shareConfigBean.setImgUrl(goodsBean.getImage());
        shareConfigBean.setLink(url);
        modelMap.put("share", shareConfigBean);
        modelMap.put("parentId", StringUtils.isEmpty(parentId) ? "0" : parentId);
        BusinessUtil.getIpAddr();
        return "web/skillDetail";
    }

    /**
     * 拼团
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/groupGoods", method = RequestMethod.GET)
    public String groupGoods(ModelMap modelMap) throws Exception {
        modelMap.put("data", groupGoodsService.getGroupGoods());
        BusinessUtil.getIpAddr();
        return "web/groupGoods";
    }

    @RequestMapping(value = "/groupDetail/{id}", method = RequestMethod.GET)
    public String groupDetail(ModelMap modelMap, @PathVariable("id") String id, HttpServletRequest request, String parentId, @CookieValue("openId") String openId) throws WxErrorException {
        GroupGoodsBean groupGoodsBean = groupGoodsService.selectById(Integer.parseInt(id));
        if (groupGoodsBean != null) {
            int viewNum = null == groupGoodsBean.getViewNum() ? 0 : groupGoodsBean.getViewNum();
            groupGoodsBean.setViewNum(viewNum + 1);
            groupGoodsService.mofiySimpleData(groupGoodsBean);
        }
        GoodsBean goodsBean = goodsService.detail(groupGoodsBean.getGoodsId());
        if(null == goodsBean){
            modelMap.put("msg","商品已下架");
            return "web/error";
        }
        modelMap.put("groupData", groupGoodsBean);
        modelMap.put("data", goodsBean);
        modelMap.put("comment", goodsCommentService.selectByGoodsId(goodsBean.getId(), 0, modelMap));
        String url = String.format("%sweb/shareDetail/%s/%s/%s", weiXinConfig.getDomian(), groupGoodsBean.getId(), openId, "2");
        ShareConfigBean shareConfigBean = WeiXinShareUtil.getWxConfig(request, weiXinConfig.getAppId(), wxMpService.getTicket(TicketType.JSAPI));
        shareConfigBean.setTitle("拼团商品，为您推荐>>>");
        shareConfigBean.setDesc(groupGoodsBean.getGoodsName());
        shareConfigBean.setImgUrl(groupGoodsBean.getGoodsImage());
        shareConfigBean.setLink(url);
        modelMap.put("share", shareConfigBean);
        modelMap.put("parentId", StringUtils.isEmpty(parentId) ? "0" : parentId);
        BusinessUtil.getIpAddr();
        return "web/groupDetail";
    }

    /**
     * 我的订单
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myOrder", method = RequestMethod.GET)
    public String myOrder(ModelMap modelMap, @CookieValue("openId") String openId, @RequestParam(defaultValue = "1") String status) throws Exception {
        modelMap.put("data", orderService.selectByOpenId(openId, status, modelMap));
        modelMap.put("status", Integer.parseInt(status));
        BusinessUtil.getIpAddr();
        return "web/myOrder";
    }

    /**
     * type 1直接购买 2购物车购买
     *
     * @param modelMap
     * @param orderSeq
     * @param openId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/orderSubmit/{orderSeq}", method = RequestMethod.GET)
    public String orderSubmit(ModelMap modelMap, @PathVariable String orderSeq, @CookieValue("openId") String openId) throws Exception {
        List<UserAddresBean> list = userAddressService.selectByOpenId(openId);
        UserAddresBean selectBean = null;
        if (CollectionUtils.isNotEmpty(list)) {
            for (UserAddresBean userAddresBean : list) {
                if (userAddresBean.getIsDefault() == 1) {
                    selectBean = userAddresBean;
                    break;
                }
            }
        }
        modelMap.put("orderSeq", orderSeq);
        modelMap.put("address", list);
        modelMap.put("selectAddress", selectBean);
        modelMap.put("goods", orderService.selectOrderGoodsByOrderId(orderSeq, modelMap));
        modelMap.put("user", userService.selectByOpenId(openId));
        BusinessUtil.getIpAddr();
        return "web/orderSubmit";
    }

    @RequestMapping(value = "/orderDetail/{orderSeq}", method = RequestMethod.GET)
    public String orderDetail(ModelMap modelMap, @PathVariable String orderSeq) throws Exception {
        modelMap.put("data", orderService.selectMergeDetail(orderSeq));
        BusinessUtil.getIpAddr();
        return "web/orderDetail";
    }

    /**
     * 我的二维码
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/qrCode", method = RequestMethod.GET)
    public String qrCode(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        BusinessUtil.getIpAddr();
        UserBean userBean = userService.selectByOpenId(openId);
        if (null == userBean) {
            modelMap.put("msg", "当前用户不存在 请联系管理员");
            return "web/applyResult";
        } else {
            if (userBean.getIsSpread() == 0) {
                modelMap.put("msg", "您目前不是合伙人 请先申请合伙人");
                return "web/applyResult";
            } else {
                modelMap.put("image", userBean.getUserSign());
                return "web/qrCode";
            }
        }

    }

    @RequestMapping(value = "/scoreInfo", method = RequestMethod.GET)
    public String scoreInfo(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        modelMap.put("data", scoreService.getScoreInfoByOpenId(openId, modelMap));
        BusinessUtil.getIpAddr();
        return "web/scoreInfo";
    }

    @RequestMapping(value = "/acctbkInfo", method = RequestMethod.GET)
    public String acctbkInfo(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        modelMap.put("recommend", goodsService.getRecommendGoods());
        modelMap.put("data", acctbkService.getAcctbkInfoByOpenId(openId));
        BusinessUtil.getIpAddr();
        return "web/acctbkInfo";
    }

    /**
     * 我的收藏
     *
     * @param modelMap
     * @param openId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myCollect", method = RequestMethod.GET)
    public String myCollect(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        List<GoodsBean> goodsBeanList = goodsCollectService.selectByOpenId(openId);
        modelMap.put("data", goodsBeanList);
        if (CollectionUtils.isEmpty(goodsBeanList)) {
            modelMap.put("recommend", goodsService.getRecommendGoods());
        }
        BusinessUtil.getIpAddr();
        return "web/myCollect";
    }

    @RequestMapping(value = "/getCash", method = RequestMethod.GET)
    public String getCash(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        modelMap.put("data", acctbkService.getAcctbkInfoByOpenId(openId));
        BusinessUtil.getIpAddr();
        return "web/getCash";
    }

    @RequestMapping(value = "/userSetting", method = RequestMethod.GET)
    public String userSetting(ModelMap modelMap, @CookieValue("openId") String openId) throws Exception {
        modelMap.put("data", userService.selectByOpenId(openId));
        BusinessUtil.getIpAddr();
        return "web/userSetting";
    }

    /**
     * 申请成为掌柜
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/bossApply", method = RequestMethod.GET)
    public String bossApply(ModelMap modelMap) throws Exception {
        BusinessUtil.getIpAddr();
        return "web/bossApply";
    }

    /**
     * 申请成为合伙人
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/partnerApply", method = RequestMethod.GET)
    public String partnerApply(ModelMap modelMap) throws Exception {
        BusinessUtil.getIpAddr();
        return "web/partnerApply";
    }

    /**
     * 申请成为VIP
     *
     * @param modelMap
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/vipApply", method = RequestMethod.GET)
    public String vipApply(ModelMap modelMap) throws Exception {
        BusinessUtil.getIpAddr();
        return "web/vipApply";
    }

    /**
     * 我的粉丝
     *
     * @param modelMap
     * @param openId
     * @param search
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/myFans", method = RequestMethod.GET)
    public String myFans(ModelMap modelMap, @CookieValue("openId") String openId, String search) throws Exception {
        List<SpreadInfoBean> spreadInfoBeanList = spreadInfoService.selectChilds(openId, search);
        modelMap.put("data", spreadInfoBeanList);
        modelMap.put("total", CollectionUtils.isNotEmpty(spreadInfoBeanList) ? spreadInfoBeanList.size() : 0);
        BusinessUtil.getIpAddr();
        return "web/myFans";
    }

    @RequestMapping(value = "/resetApply/{type}", method = RequestMethod.GET)
    public String resetApply(ModelMap modelMap, @PathVariable Integer type, @CookieValue("openId") String openId) throws Exception {
        applyInfoService.deleteByOpenIdAndType(openId, type);
        if (type == 1) {
            return "forward:/web/vipApply";
        } else if (type == 2) {
            return "forward:/web/partnerApply";
        } else if (type == 3) {
            return "forward:/web/bossApply";
        }
        BusinessUtil.getIpAddr();
        return "web/applyResult";
    }

    @RequestMapping(value = "/applyResult/{type}", method = RequestMethod.GET)
    public String applyResult(ModelMap modelMap, @PathVariable Integer type, @CookieValue("openId") String openId) throws Exception {
        List<ApplyInfoBean> list = applyInfoService.selectByOpenIdAndType(openId, type);
        if (CollectionUtils.isEmpty(list)) {
            if (type == 1) {
                return "forward:/web/vipApply";
            } else if (type == 2) {
                return "forward:/web/partnerApply";
            } else if (type == 3) {
                return "forward:/web/bossApply";
            }
        } else {
            int status = list.get(0).getStatus();
            modelMap.put("status", status);
            modelMap.put("type", type);
            if (status == 0) {
                modelMap.put("msg", "提交审核，申请中……");
            } else if (status == 1) {
                if (type == 1) {
                    modelMap.put("msg", "申请通过，您已是VIP用户……");
                } else if (type == 2) {
                    modelMap.put("msg", "申请通过，您已是平台合伙人……");
                } else if (type == 3) {
                    UserBean userBean = userService.selectByOpenId(openId);
                    StringBuilder sb = new StringBuilder();
                    sb.append("申请通过，您已是平台掌柜……").append("<br>");
                    if (null != userBean) {
                        String url = String.format("<a href='%s'>%s</a>", weiXinConfig.getDomian() + "admin", weiXinConfig.getDomian() + "admin");
                        sb.append("后台地址：").append(url).append("<br>");
                        sb.append("分配账号：").append(userBean.getAccountName()).append(" 分配密码：").append(userBean.getPassword());
                    }
                    modelMap.put("msg", sb.toString());
                }
                return "web/applyResult";
            } else if (status == 2) {
                modelMap.put("msg", "申请失败，原因：" + list.get(0).getRemark());
                return "web/applyResult";
            } else if (status == -1) {
                modelMap.put("msg", "未支付或未购买商品");
            }
        }
        BusinessUtil.getIpAddr();
        return "web/applyResult";
    }

    @RequestMapping(value = "/payFail/{orderSeq}", method = RequestMethod.GET)
    public String payFail(ModelMap modelMap, @PathVariable String orderSeq, String orderTime, String totalFee) throws Exception {
        String orderType = orderSeq.substring(orderSeq.length() - 1, orderSeq.length());
        modelMap.put("orderType", Integer.parseInt(orderType));
        modelMap.put("orderSeq", orderSeq);
        modelMap.put("orderTime", orderTime);
        modelMap.put("totalFee", totalFee);
        BusinessUtil.getIpAddr();
        return "web/payFail";
    }

    @RequestMapping(value = "/paySuccess/{orderSeq}", method = RequestMethod.GET)
    public String paySuccess(ModelMap modelMap, @PathVariable String orderSeq, String orderTime, String totalFee) throws Exception {
        String orderType = orderSeq.substring(orderSeq.length() - 1, orderSeq.length());
        modelMap.put("orderType", Integer.parseInt(orderType));
        modelMap.put("orderSeq", orderSeq);
        if (StringUtils.isEmpty(orderTime) || StringUtils.isEmpty(totalFee)) {
            List<OrderBean> orderBeanList = orderService.selectByOrderId(orderSeq);
            if (CollectionUtils.isNotEmpty(orderBeanList)) {
                int totalMoney = 0;
                String orderTimeStr = null;
                for (OrderBean orderBean : orderBeanList) {
                    totalMoney += orderBean.getTotalPrice();
                    if (StringUtils.isEmpty(orderTimeStr)) {
                        orderTimeStr = BusinessUtil.date2TimeStr(orderBean.getCreateDate(), "yyyy-MM-dd HH:mm:ss");
                    }
                }
                modelMap.put("orderTime", orderTimeStr);
                modelMap.put("totalFee", BusinessUtil.getWebAmount(totalMoney));
            }
        } else {
            modelMap.put("orderTime", orderTime);
            modelMap.put("totalFee", totalFee);
        }
        BusinessUtil.getIpAddr();
        return "web/paySuccess";
    }

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessage upload(HttpServletRequest request) throws Exception {
        JSONObject jsonObject = FileUploadUtil.uploadOssFile(request, isLocal);
        ResultMessage resultMessage = new ResultMessage();
        resultMessage.setData(jsonObject.containsKey("src") ? jsonObject.get("src") : "");
        BusinessUtil.getIpAddr();
        return resultMessage;
    }
}
